<!DOCTYPE HTML>
<html>
<head>
<title>WebSocket</title>
<meta charset="UTF-8">
<meta http-equiv="content-type" content="text/html">
<!--  
<meta http-equiv="refresh" content="10;url=http://127.0.0.1:8080/websocket">
-->
<!-- 页面所代表的 Web 应用程序的名称 -->
<meta name="application-name" content="kaizhong.net">
<!-- 告诉搜索引擎你的站点的主要内容 -->
<meta name="description" content="websocket study demo">
<!-- 用以说明生成工具 -->
<meta name="generator" content="eclipse">
<!-- 向搜索引擎说明你的网页的关键词 -->
<meta name="keywords" content="websocket,html5,java">
<!-- 告诉搜索引擎你的站点的制作的作者 -->
<meta name="author" content="huqifeng">

<script type="text/javascript">
	var websocket = null;

	function connect() {
		var userCode = document.getElementById('usercode');
		var target = "ws://localhost:8080/websocket/chat/";
		target = target + userCode.value;
		
		//判断当前浏览器是否支持 WebSocket
		if ('WebSocket' in window) {
			websocket = new WebSocket(target);
		}else if ('MozWebSocket' in window) {
			websocket = new MozWebSocket(target);
		}
		else {
			alert('Not support websocket')
		}

		//连接发生错误的回调方法
		websocket.onerror = function() {
			setMessageInnerHTML("error");
		};

		//连接成功建立的回调方法
		websocket.onopen = function(event) {
			setMessageInnerHTML("open");
		}

		//接收到消息的回调方法
		websocket.onmessage = function(event) {
			setMessageInnerHTML(event.data);
		}

		//连接关闭的回调方法
		websocket.onclose = function() {
			setMessageInnerHTML("close");
		}
	}

	//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常
	window.onbeforeunload = function() {
		websocket.close();
		websocket = null;
	}

	//将消息显示在网页上
	function setMessageInnerHTML(msg) {
		var console = document.getElementById('message');
		var p = document.createElement('p');
		p.appendChild(document.createTextNode(msg));
		console.appendChild(p);
		while (console.childNodes.length > 10) {
			console.removeChild(console.firstChild);
		}
	}

	//关闭连接
	function closeWebSocket() {
		websocket.close();
		websocket = null;
	}

	//发送消息
	function send() {
		var message = document.getElementById('text').value;
		if (null != websocket) {
			websocket.send(message);
			document.getElementById('text').value='';
		} else {
			setMessageInnerHTML('You need reconnect.');
		}
	}
</script>
</head>

<body>
	Welcome
	<br />
	<input id="usercode" type="text" value="admin" maxlength="20" placeholder="请输入登录账号" />
	<button onclick="connect()">Login</button>
	<br />
	<br />
	<input id="text" type="text" />
	<button onclick="send()">Send</button>
	<button onclick="closeWebSocket()">Close</button>
	<button onclick="connect()">ReConnect</button>
	<div id="message"></div>
</body>

</html>